import hashlib
from django.contrib.auth import logout
from django.dispatch import Signal
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from blog.models import User


# Create your views here.
def login_view(request):
    # return render(request, 'login1.html')
    if request.method == 'GET':
        # 检查登录状态
        if request.session.get('username') and request.session.get('uuid'):
            return HttpResponse('see已登录')
        elif request.COOKIES.get('username') and request.COOKIES.get('uuid'):
            request.session['username'] = request.COOKIES.get('username')
            request.session['uuid'] = request.CooKIES.get('uuid')
            return HttpResponse('cook已登录')
        return render(request, 'login.html')

    elif request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        print('fhruithrith5rui')
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            return HttpResponse('用户名不存在')

        try:
            md = hashlib.md5()
            md.update(password.encode())
            md_password = md.hexdigest()
            if md_password != user.password:
                return HttpResponse('密码错误')
        except Exception as e:
            print(f"密码异常{e}")
            return HttpResponse('密码异常')
        request.session['username'] = username
        request.session['uuid'] = user.id
        resp = HttpResponse('登陆成功')
        if 'remember' in request.POST:
            resp.set_cookie('username', username, 3600 * 24 * 3)
            resp.set_cookie('uuid', user.id, 3600 * 24 * 3)
        return resp


def login_page(request):
    if request.method == 'GET':
        if request.COOKIES.get('username') and request.COOKIES.get('uuid'):
            return HttpResponse('已登录')
        elif request.session.get('username') and request.session.get('uuid'):
            return HttpResponse('已登录')
        else:
            return render(request, 'login.html')
    elif request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        print('HUDHWWWWWWWWWWWWWWWW')
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            return HttpResponse('用户名不存在')

        # user = User.objects.get(username=username)
        # if not user:
        #     return HttpResponse('用户不存在')

        md = hashlib.md5()
        md.update(password.encode())
        password = md.hexdigest()
        # print(f"加密的后的密码是{password}")

        if password != user.password:
            return HttpResponse('密码错误')

        request.session['username'] = username
        request.session['uuid'] = user.id

        resp = HttpResponse('登陆成功')
        if 'remember' in request.POST:
            resp.set_cookie('username', username, 3600 * 24 * 7)
            resp.set_cookie('uuid', user.id, 3600 * 24 * 7)
        return resp


def reg_view(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    elif request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        old_users = User.objects.filter(username=username)
        if old_users:
            return HttpResponse('用户名已注册')
        md = hashlib.md5()
        md.update(password.encode())
        password = md.hexdigest()
        print(f"加密的后的密码是{password}")
        User.objects.create(username=username, password=password)
        request.session['username'] = username
        return HttpResponseRedirect('/blog/index/')


def index(request):
    return render(request, 'index.html')


def logout_view(request):
    # user_logged_out = Signal()
    # user = getattr(request, "username", None)
    # print("popopop")
    # if not getattr(user, "is_authenticated", True):
    #     user = None
    # user_logged_out.send(sener=user.__class__, request=request, username=user)
    # request.session.flush()
    # if hasattr(request, "username"):
    #     from django.contrib.models import AnonymousUser
    #
    #     request.user = AnonymousUser
    logout(request)
    return HttpResponseRedirect('/blog/index/')
